package utils;

/**
 * Created by zqx on 15/11/10.
 */
public class TextUtils {
    /**
     * Returns true if the string is null or 0-length.
     *
     * @param str the string to be examined
     * @return true if str is null or zero length
     */
    public static boolean isEmpty(CharSequence str) {
        if (str == null || str.length() == 0)
            return true;
        else
            return false;
    }

    /**
     * Returns the length that the specified CharSequence would have if
     * spaces and control characters were trimmed from the start and end,
     * as by {@link String#trim}.
     */
    public static int getTrimmedLength(CharSequence s) {
        int len = s.length();

        int start = 0;
        while (start < len && s.charAt(start) <= ' ') {
            start++;
        }

        int end = len;
        while (end > start && s.charAt(end - 1) <= ' ') {
            end--;
        }

        return end - start;
    }

    public static String stringOf(Object object, String back) {
        if (object == null)
            return back;
        else
            return object.toString();
    }

    public static String stringOf(Object object) {
        return stringOf(object, "null");
    }

    public static Boolean isNumber(String str) {
        return str != null && str.matches("[0-9]*");
    }

    public static Integer parseInt(String str,int standby){
        if(str == null) return standby;
        try {
            return Integer.parseInt(str);
        }catch (NumberFormatException e){
            return standby;
        }
    }

    public static Double parseDouble(String str,Double standby){
        if(str == null) return standby;
        try {
            return Double.parseDouble(str);
        }catch (NumberFormatException e){
            return standby;
        }
    }

    public static String getFileRandomName(String superaddition){
        String name = System.currentTimeMillis() + "_";
        int random = (int) (Math.random() * 9000 + 1000);
        name += random;
        if(superaddition != null){
            name += "_" + superaddition;
        }
        return name;
    }
}
